/* global  expect, apiTest */

require('../../apiTest')

const Admin = {}

// 生成随机提交数据
Admin.randOne = () => {
  // 临时密码
  var passwd = apiTest.random(10000000, 99999999) + ''
  return {
    username: 'autoTest' + (new Date()).getTime(),
    mobile: '138' + apiTest.random(10000000, 99999999),
    password: passwd,
    // password2: passwd,
    role: '5a7bf5c08126ea5cd49b9fb6'
  }
}

// 列表单条验证
Admin.checkOne = v => {
  expect(v).to.be.an('object')
  apiTest.isObjectId(v._id)
  expect(v.username).to.be.an('string')
  if (v.role) expect(v.role).to.be.an('string')
  expect(v.status).to.be.a('number')
  if (v.last) {
    expect(v.last).to.be.an('object')
    expect(v.last.login).to.be.an('string')
    apiTest.isIp(v.last.ip)
  }
}

// 列表通用验证
Admin.checkList = (get, cb) => {
  // console.log(Object.assign({}, get))
  return apiTest.get('/admin/find', Object.assign({}, get)).then(function(res) {
    var data = apiTest.apiOk(res)
    expect(data).to.be.a('object')
    // 验证分页
    apiTest.checkPaging(data)
    data.list.forEach(function(v) {
      Admin.checkOne(v)
      if (cb) cb(v)
    })
  })
}

// 删除用户
Admin.removeOne = (_id, cb) => {
  let num = 1
  if (Array.isArray(_id)) num = _id.length
  return apiTest.post('/admin/remove', { _id: _id }).then(function(res) {
    // console.log(res.data)
    var data = apiTest.apiOk(res)
    expect(data.ok).to.equal(1)
    expect(data.n).to.equal(num)
    if (cb) return cb()
  })
}

// 修改用户并查询验证
Admin.editOne = function(_id, post, cb) {
  post.mail = post.mobile + '@qq.com'
  post.status = 0
  post._id = _id
  return apiTest.post('/admin/update?_id=' + _id, post).then(function(res) {
    apiTest.apiOk(res)
    // 查
    return apiTest.get('/admin/findOne', { _id: _id }).then(function(res) {
      var data = apiTest.apiOk(res)
      expect(data.username).to.not.equal(post.username, '用户名不能变更')
      expect(data.mobile).to.equal(post.mobile)
      expect(data.mail).to.equal(post.mail)
      expect(data.status).to.equal(post.status)
      expect(data.role).to.equal(post.role)
      if (cb) return cb(data, post)
    })
  })
}
// 添加用户
Admin.addOne = function(post, cb) {
  return apiTest.post('/admin/create', post).then(function(res) {
    var data = apiTest.apiOk(res)
    Admin.checkOne(data)
    expect(data.status).to.equal(post.status || 0) // 默认值
    expect(data.username).to.equal(post.username)
    expect(data.mobile).to.equal(post.mobile)
    expect(data.role).to.equal(post.role)
    if (cb) return cb(data)
  })
}
// 登录验证
Admin.login = function(post, cb) {
  return apiTest.post('/account/login', post).then(function(res) {
    var data = apiTest.apiOk(res)
    if (cb) return cb(data)
  })
}

// 数量统计
Admin.count = function(con, cb) {
  return apiTest.get('/admin/count', con).then(function(res) {
    var data = apiTest.apiOk(res)
    if (cb) return cb(data)
  })
}

module.exports = Admin
